<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul
          class="cart-list"
          v-for="shopCart in shopCartList"
          :key="shopCart.id"
        >
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="!!shopCart.isChecked"
              @change="checkCartState(shopCart)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="shopCart.imgUrl" />
            <div class="item-msg">{{ shopCart.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ shopCart.skuPrice }}.00</span>
          </li>
          <li class="cart-list-con5">
            <a
              href="javascript:void(0)"
              class="mins"
              @click="changeSkuNum('decrement', shopCart)"
              >-</a
            >
            <input
              autocomplete="off"
              type="text"
              :value="shopCart.skuNum"
              minnum="1"
              class="itxt"
              @change="changeSkuNum('change', shopCart, $event)"
            />
            <a
              href="javascript:void(0)"
              class="plus"
              @click="changeSkuNum('increment', shopCart)"
              >+</a
            >
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ shopCart.skuPrice * shopCart.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a
              href="javascript:;"
              @click="showDialogByDelOne(shopCart.skuId)"
              class="sindelet"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="showDialogByDelAll">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ selectCount }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ selectMoney }}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade">结算</router-link>
        </div>
      </div>
    </div>

    <!-- 弹窗组件 -->
    <!-- <Dialog :visible="visible" @btnClose="btnClose"> -->
    <!-- <Dialog :visible="visible" @btnClose:visible="btnClose"> -->
    <!-- <Dialog :visible="visible" @btnClose:visible="visible = $event"> -->
    <Dialog :visible.sync="visible">
      <template v-slot:header>
        <p>提示</p>
      </template>
      <template>
        <p>您确定要删除{{ isDelOne ? "这件" : "所选" }}商品吗</p>
      </template>
      <!-- <template v-slot:footer> -->
      <template #footer>
        <div class="btn-footer">
          <button class="btn btn-cancle" @click="visible = false">取消</button>
          <button class="btn btn-primary" @click="delShopCartInfo">确定</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import {
  reqGetShopCartListData,
  reqChangeShopCartInfoState,
  reqChangeAllCartState,
  reqDelOneShopCartInfo,
  reqDelAllShopCartInfo,
  reqAddOrUpdateCart,
} from "@/api"
import { skuNumReg } from "@/utils/reg"
import { Message } from "element-ui"
export default {
  name: "ShopCart",
  data() {
    return {
      shopCartList: [], // 当前购物车中要渲染的数据
      visible: false, // 对话框是否显示
      skuId: "", // 商品id
      isDelOne: false, // 是否删除一条
      skuIdList: [], // 待删除的商品id
      itemId: "", // 计时器存储
      num: 0, // 需要发送给服务器的商品数量
    }
  },
  // async mounted() {
  //   const result = await reqGetShopCartListData()
  //   if (result.code === 200) {
  //     // console.log("添加购物车成功", result.data)
  //     // console.log("添加购物车成功", result.data[0])
  //     this.shopCartList = result.data.length ? result.data[0].cartInfoList : []
  //   } else {
  //     console.log("添加购物车失败", result.message)
  //   }
  // },
  mounted() {
    this.getShopCartListData()
  },
  methods: {
    // 封装获取购物车数据
    async getShopCartListData() {
      const result = await reqGetShopCartListData()
      if (result.code === 200) {
        // console.log("添加购物车成功", result.data)
        // console.log("添加购物车成功", result.data[0])
        this.shopCartList = result.data.length
          ? result.data[0].cartInfoList
          : []
      } else {
        console.log("添加购物车失败", result.message)
      }
    },
    // 修改购物车中商品选中状态
    async checkCartState(shopCart) {
      // let isChecked = shopCart.isChecked === 0 ? 1 : 0
      let isChecked = 1 - shopCart.isChecked
      // console.log(shopCart.skuId, isChecked)
      const result = await reqChangeShopCartInfoState(shopCart.skuId, isChecked)
      if (result.code === 200) {
        // this.$message({
        //   message: "商品状态更新成功...",
        //   type: "success",
        // })
        Message.success("商品状态更新成功...")
        // 让页面中的状态发生改变一下
        // console.log("单选请求成功")
        shopCart.isChecked = isChecked
      } else {
        this.$message({
          message: "商品状态更新失败...",
          type: "error",
        })
        console.log(result.message)
      }
    },
    // 关闭弹窗
    // btnClose(value) {
    //   this.visible = value
    // },
    // 删除商品并弹出对话框
    showDialogByDelOne(id) {
      this.skuId = id
      this.visible = true
      // 删除一条商品
      this.isDelOne = true
    },
    async delShopCartInfo() {
      if (this.isDelOne === true) {
        // 删除一条
        const result = await reqDelOneShopCartInfo(this.skuId)
        // console.log("删除一条数据")
        if (result.code === 200) {
          // console.log("删除数据请求成功", result)
          // 重新渲染页面
          // this.getShopCartListData()

          // 性能优化,节省一次请求
          this.shopCartList = this.shopCartList.filter(
            (item) => item.skuId !== this.skuId
          )

          // 关掉弹框
          this.visible = false
        } else {
          console.log("删除数据失败", result.message)
        }
      } else {
        // 删除选中
        const result = await reqDelAllShopCartInfo(this.skuIdList)
        // console.log("删除选中数据")
        if (result.code === 200) {
          // console.log("删除数据请求成功", result)
          // 重新渲染页面
          // this.getShopCartListData()

          // 性能优化,节省一次请求
          this.shopCartList = this.shopCartList.filter(
            (item) => (item.skuId !== item.isChecked) === 0
          )

          // 关掉弹框
          this.visible = false
        } else {
          console.log("删除数据失败", result.message)
        }
      }
    },
    // 批量删除弹窗
    showDialogByDelAll() {
      this.isDelOne = false
      this.visible = true
      // 收集选中商品id
      // const skuIdList = []
      this.shopCartList.forEach((shopCart) => {
        if (shopCart.isChecked == 1) {
          // this.skuIdList.push(shopCart.skuId)
          this.skuIdList.push(shopCart.skuId)
          // console.log(this.skuIdList)
        }
      })
    },
    // 更新商品数量
    changeSkuNum(type, cartInfo, e) {
      // let num = 0
      let oldNum = cartInfo.skuNum // 存储原值
      if (type === "decrement") {
        // console.log("decrement--->")
        this.num--
        cartInfo.skuNum--
        if (cartInfo.skuNum < 1) {
          cartInfo.skuNum = 1
          // num = 0
          this.num = 1 - oldNum
        }
      } else if (type === "increment") {
        // console.log("increment--->")
        this.num++
        cartInfo.skuNum++
        if (cartInfo.skuNum > 200) {
          cartInfo.skuNum = 200
          // num = 0
          this.num = 200 - oldNum
        }
      } else {
        // console.log("change--->")
        let newNum = e.target.value // 用户新输入的数据
        // let oldNum = cartInfo.skuNum
        if (skuNumReg.test(newNum)) {
          // 页面中显示出来的值
          cartInfo.skuNum = newNum
          // 发送给服务器的差值
          this.num = newNum - oldNum
          if (newNum > 200) {
            // console.log("大于200了...")
            cartInfo.skuNum = 200
            this.num = 200 - oldNum
          }
        } else {
          // 如果输入用户的是非法值 还是让结果为原值
          // cartInfo.skuNum = oldNum
          e.target.value = oldNum
        }
      }

      // console.log(num)
      if (this.num === 0) return
      if (this.timeId) clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        // 发送请求
        const result = await reqAddOrUpdateCart(cartInfo.skuId, this.num)
        if (result.code === 200) {
          this.num = 0
          console.log("更新商品数量成功")
        } else {
          console.log("更新商品数量失败", result.message)
        }
      }, 1000)
    },
  },
  computed: {
    // 全选全不选
    checkAll: {
      get() {
        return (
          this.shopCartList.every((item) => item.isChecked === 1) &&
          this.shopCartList.length
        )
      },
      async set(value) {
        console.log(value)
        let isChecked = value ? 1 : 0
        // 定义一个变量数组,来存储所有要更新状态的商品skuId
        const skuIdList = []
        this.shopCartList.forEach((item) => {
          item.isChecked = isChecked
          skuIdList.push(item.skuId)
          // 更新每一个商品的选中状态
          // this.checkCartState({ skuId: item.skuId, isChecked: 1 - isChecked })
        })

        // 统一更新选中状态
        const result = await reqChangeAllCartState(isChecked, skuIdList)
        if (result.code === 200) {
          console.log("更新成功")
        } else {
          console.log("更新失败")
        }
      },
    },
    // 选中商品的数量
    selectCount() {
      // return this.shopCartList.filter((item) => item.isChecked === 1).length
      return this.shopCartList.reduce(
        (prev, current) => prev + current.isChecked,
        0
      )
    },
    // 选中商品的总价
    selectMoney() {
      return this.shopCartList.reduce(
        (prev, current) =>
          prev + current.isChecked * current.skuPrice * current.skuNum,
        0
      )
    },
  },
}
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
.btn-footer {
  position: absolute;
  right: 30px;
  bottom: 20px;
  .btn {
    width: 60px;
    height: 30px;
    font-size: 16px;
    color: #666;
    margin-right: 6px;
    cursor: pointer;
    border: none;
    border-radius: 5px;
    background-color: rgba(124, 124, 124, 0.233);
  }
  .btn-primary {
    background-color: rgba(0, 174, 255, 0.349);
  }
}
</style>
